/*
 *  Setup.java prompts the user for information about two contacts which it saves persistently and passes to Master.java when loaded 
 *  Copyright (C) 2010  Andrew Fasano
 *
 *   This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.tds.master;
/*
 */


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

//This code could all be removed if setup was updated to simply used a savedpreferences object

public class Setup extends Activity {
	private static final String TAG = "TDS-Setup";
	public final int PICK_CONTACT = 1;
	Settings settings = new Settings();
	String savedName, savedNumber, savedEmail;
	SharedPreferences.Editor editor;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG,"Created");
		final SharedPreferences savedSettings = getPreferences(0);
        setContentView(R.layout.setup_c1);

		Boolean update = false;
		if (getIntent().getExtras() != null)
			update = getIntent().getExtras().containsKey("update"); //setup can be called with an extra key of update to update the settings when they already exist
		
		if (savedSettings.contains("contact1phone") && savedSettings.contains("contact2phone") && !update) { 
			settings.setContact(1, savedSettings.getString("contact1name", null), savedSettings.getString("contact1phone", null), savedSettings.getString("contact1email",null));	
			settings.setContact(2, savedSettings.getString("contact2name", null), savedSettings.getString("contact2phone", null), savedSettings.getString("contact2email",null));	
			Log.i(TAG,"Settings data has been loaded and no update flag was sent, going to waiting");
	    	Intent i = new Intent(getApplicationContext(), Master.class);
			i.putExtra("contact1name", settings.contact1[0]);
			i.putExtra("contact1phone", settings.contact1[1]);
			i.putExtra("contact1email", settings.contact1[2]);
			i.putExtra("contact2name", settings.contact2[0]);
			i.putExtra("contact2phone", settings.contact2[1]);
			i.putExtra("contact2email", settings.contact2[2]);
			
	    	startActivity(i);
	    	}
		
				
		
        setContentView(R.layout.setup_c1);
        Button next = (Button) findViewById(R.id.done);
        Button select = (Button) findViewById(R.id.select);
        
		if ((savedName = settings.contact1[0]) != null) {
        	((TextView) findViewById(R.id.name)).setText(savedName);
        }

		if ((savedNumber = settings.contact1[1]) != null) {
        	((TextView) findViewById(R.id.number)).setText(savedNumber);
        }
		
		if ((savedEmail = settings.contact1[2]) != null) {
        	((TextView) findViewById(R.id.email)).setText(savedEmail);
        }

		
        select.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectContact();
			}    	
        });
        
        next.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				String name = ((EditText) findViewById(R.id.name)).getText().toString();
				String number =  ((EditText) findViewById(R.id.number)).getText().toString();
				String email =  ((EditText) findViewById(R.id.email)).getText().toString();

				settings.setContact(1, name, number, email);
				editor = savedSettings.edit();
				editor.putString("contact1name", name);
				editor.putString("contact1phone", ""+number);
				editor.putString("contact1email", email);
				editor.commit();
				
				setContentView(R.layout.setup_c2);
				
				Button finish = (Button) findViewById(R.id.done2);
		        Button select2 = (Button) findViewById(R.id.select2);
		        
				if ((savedName = settings.contact2[0]) != null) {
		        	((TextView) findViewById(R.id.name)).setText(savedName);
		        }

				if ((savedNumber = settings.contact2[1]) != null) {
		        	((TextView) findViewById(R.id.number)).setText(savedNumber);
		        }
				
				if ((savedEmail = settings.contact2[2]) != null) {
		        	((TextView) findViewById(R.id.email)).setText(savedEmail);
		        }
				
		        select2.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						selectContact();
					}    	
		        });
					        
		        finish.setOnClickListener(new OnClickListener() {
		        	public void onClick(View arg0) {
						String name = ((EditText) findViewById(R.id.name)).getText().toString();
						String number =  ((EditText) findViewById(R.id.number)).getText().toString();
						String email =  ((EditText) findViewById(R.id.email)).getText().toString();

						settings.setContact(1, name, number, email);
						editor = savedSettings.edit();
						editor.putString("contact2name", name);
						editor.putString("contact2phone", ""+number);
						editor.putString("contact2email", email);
						editor.commit();
		        		
						Log.i(TAG,"Settings data has been created. Going to WatingForDock");
				    	Intent i = new Intent(getApplicationContext(), Master.class);
						i.putExtra("contact1name", settings.contact1[0]);
						i.putExtra("contact1phone", settings.contact1[1]);
						i.putExtra("contact1email", settings.contact1[2]);
						i.putExtra("contact2name", settings.contact2[0]);
						i.putExtra("contact2phone", settings.contact2[1]);
						i.putExtra("contact2email", settings.contact2[2]);
				    	startActivity(i);
				    }        
		        }); 
			}
        });       
	}
	
    public void selectContact() {
    	Log.d(TAG,"Select Contacts was called");
    	Intent intent = new Intent(Intent.ACTION_PICK, android.provider.ContactsContract.Contacts.CONTENT_URI);
    	startActivityForResult(intent, PICK_CONTACT);
    }
    
    
    //This is called from selectContacts
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
    	super.onActivityResult(reqCode, resultCode, data);
  		Log.d(TAG,"OnActivityResult has been called");
  		switch (reqCode) {
	      case (PICK_CONTACT):
	        if (resultCode == Activity.RESULT_OK) {
		      Uri contactData = data.getData();
		      Cursor c =  managedQuery(contactData, null, null, null, null);
		      if (c.moveToFirst()) {
		    	  //This adds a column to the uri called MIMETYPE with a value of the mimetype. This is used later to check if it's a phone number 
		            Uri contactsData = ContactsContract.Contacts.CONTENT_URI.buildUpon()
	                .appendPath(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)))
	                .appendPath(ContactsContract.Contacts.Data.CONTENT_DIRECTORY).build();

		            
	            Log.d(TAG, "contacts data uri: " + contactsData.toString());
	            Cursor c2 = managedQuery(contactsData, null, ContactsContract.Contacts.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'", null, null);
	          
	            Boolean hasData = false;
	            while(c2.moveToNext()) {
	            		hasData = true;
	                    String number = c2.getString(c2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	    	            String name = c2.getString(c2.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
	    	            Cursor c3 = managedQuery(contactsData, null, ContactsContract.Contacts.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE+"'", null, null);
	    	            String email = "";
	    	            
	    	            if (c3.moveToFirst()) {
	    	            	email = c3.getString(c3.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.DATA));
	    	            }
	    	            	
	                    Log.d(TAG,"Name: "+name+" && number: " + number +" && email: "+email);	    
	    		        ((TextView) findViewById(R.id.name)).setText(name);
	    		        ((TextView) findViewById(R.id.number)).setText(number);
	    		        ((TextView) findViewById(R.id.email)).setText(email);
	            }
	            
	            if (hasData) {
		            Log.d(TAG,"Has data");
	            }else{
	            	Cursor nameOnly = managedQuery(contactsData, null, null, null, null);
	            	if (nameOnly.moveToFirst()) {
	            		Log.d(TAG,"Does not have phone number.");
	            		String name = nameOnly.getString(nameOnly.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
	            		Log.d(TAG,"Name is:"+name);
	            		resetTextFields();
	    		        ((TextView) findViewById(R.id.name)).setText(name);
	            	}else{
	            		Log.e(TAG," Contact has no name.");
	            		resetTextFields();
	    		        ((TextView) findViewById(R.id.name)).setText("Error loading contact");
	    		        ((TextView) findViewById(R.id.number)).setText("Please try again");
	            	}
	            	
	            	
	            }
		      }
	        }
	      break;
      	}    
    }
    
    public void resetTextFields() {
        ((TextView) findViewById(R.id.name)).setText("");
        ((TextView) findViewById(R.id.number)).setText("");
        ((TextView) findViewById(R.id.email)).setText("");
    }    
    
	@Override
	public void onDestroy() {
		Log.i(TAG,"Destorying Setup");
		super.onDestroy();
	}

    
 }

